from rest_framework import serializers
from .models import Category, Product, SKU, Banner
from django.db.models import Min, Max

class CategorySerializer(serializers.ModelSerializer):
    icon = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ['id', 'name', 'sort_order', 'icon']

    def get_icon(self, obj):
        # 这里可以根据分类返回对应的图标URL
        # 暂时返回空字符串，让前端使用默认图标
        return ""

class SKUSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(source='product.name', read_only=True)
    product_image = serializers.ImageField(source='product.image', read_only=True)
    
    class Meta:
        model = SKU
        fields = [
            'id', 'product', 'product_name', 'product_image',
            'name', 'price', 'stock', 'image', 'is_active'
        ]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        # 确保价格是浮点数并保留两位小数
        if data['price'] is not None:
            data['price'] = float(data['price'])
        return data

class ProductSerializer(serializers.ModelSerializer):
    category_name = serializers.CharField(source='category.name', read_only=True)
    skus = SKUSerializer(many=True, read_only=True)
    default_sku = serializers.SerializerMethodField()
    price = serializers.SerializerMethodField()  # 最低价格
    price_range = serializers.SerializerMethodField()  # 价格范围
    stock = serializers.SerializerMethodField()  # 总库存
    
    class Meta:
        model = Product
        fields = [
            'id', 'name', 'description', 'image', 
            'category', 'category_name', 'skus',
            'default_sku', 'is_active', 'price',
            'price_range', 'stock'
        ]

    def get_default_sku(self, obj):
        # 获取默认SKU（这里简单地取第一个）
        sku = obj.skus.filter(is_active=True).first()
        if sku:
            return SKUSerializer(sku).data
        return {
            'id': None,
            'price': 0,
            'stock': 0,
            'name': '默认规格'
        }

    def get_price(self, obj):
        # 获取最低价格，如果没有则返回0
        min_price = obj.skus.filter(is_active=True).aggregate(min_price=Min('price'))['min_price']
        return float(min_price) if min_price is not None else 0.00

    def get_price_range(self, obj):
        # 获取价格范围
        price_range = obj.skus.filter(is_active=True).aggregate(
            min_price=Min('price'),
            max_price=Max('price')
        )
        min_price = price_range['min_price']
        max_price = price_range['max_price']
        
        if min_price is None:
            return "¥0.00"
        
        min_price = float(min_price)
        max_price = float(max_price)
        
        if min_price == max_price:
            return f"¥{min_price:.2f}"
        return f"¥{min_price:.2f} ~ ¥{max_price:.2f}"

    def get_stock(self, obj):
        # 获取总库存，如果没有则返回0
        return sum(sku.stock for sku in obj.skus.filter(is_active=True)) or 0

class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Banner
        fields = ['id', 'title', 'image', 'link', 'sort_order', 'is_active'] 